//
//  WLMapV.m
//  UTOO
//
//  Created by Lenny on 16/5/3.
//  Copyright © 2016年 asput. All rights reserved.
//

#import "WLMapV.h"

@interface WLMapV ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKRouteSearchDelegate>
{
    CLLocationCoordinate2D userCoor;
}

@end

@implementation WLMapV

#pragma mark - life cycle
- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        [self addSubview:self.mapV];
        [self initData];
    }
    return self;
}

#pragma mark - public motheds

- (void)viewWillAppear {
    
    [self.mapV viewWillAppear];
    self.mapV.delegate = self;
    _locService.delegate = self;
    _routeSearch.delegate = self;
}

- (void)viewWillDisappear {
    
    [self.mapV viewWillDisappear];
    self.mapV.delegate = nil;
    _locService.delegate = nil;
    _routeSearch.delegate = nil;
}

#pragma mark - delegate motheds

#pragma mark - delegate
- (void)mapViewDidFinishLoading:(BMKMapView *)mapView {
    
    
}

- (void)willStartLocatingUser {
    
    NSLog(@"fssfsf");
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    
    
    [_locService stopUserLocationService];
    BMKCoordinateRegion region;
    region.center = userLocation.location.coordinate;
    region.span.latitudeDelta = 0.1;
    region.span.longitudeDelta = 0.1;
    [self.mapV setRegion:region animated:NO];
    [self.mapV updateLocationData:userLocation];
    
    
    userCoor = userLocation.location.coordinate;
    
    [self addOilState];
    [self addLine];
}

- (void)didFailToLocateUserWithError:(NSError *)error {
    
    NSLog(@"failed");
}


- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation {
    
    // 生成重用标示identifier
    NSString *AnnotationViewID = @"xidanMark";
    
    // 检查是否有重用的缓存
    BMKAnnotationView* annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (annotationView == nil) {
        
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorGreen;
        // 设置重天上掉下的效果(annotation)
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
        ((BMKPinAnnotationView*)annotationView).image = [UIImage imageNamed:@"1_normal.png"];
    }
    
    // 设置位置
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    // 单击弹出泡泡，弹出泡泡前提annotation必须实现title属性
    annotationView.canShowCallout = YES;
    // 设置是否可以拖拽
    annotationView.draggable = NO;
    
    return annotationView;
}

- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
{
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.fillColor = [[UIColor alloc] initWithRed:0 green:1 blue:1 alpha:1];
        polylineView.strokeColor = [[UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0.7];
        polylineView.lineWidth = 5.0;
        return polylineView;
    }
    return nil;
}


- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:self.mapV.annotations];
    [self.mapV removeAnnotations:array];
    array = [NSArray arrayWithArray:self.mapV.overlays];
    [self.mapV removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0];
        // 计算路线方案中的路段数目
        NSInteger size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = @"起点";
                item.type = 0;
                [self.mapV addAnnotation:item]; // 添加起点标注
                
            }else if(i==size-1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = @"终点";
                item.type = 1;
                [self.mapV addAnnotation:item]; // 添加起点标注
            }
            //添加annotation节点
            //            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            //            item.coordinate = transitStep.entrace.location;
            //            item.title = transitStep.entraceInstruction;
            //            item.degree = transitStep.direction * 30;
            //            item.type = 4;
            //            [self.mapV addAnnotation:item];
            
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        // 添加途经点
        if (plan.wayPoints) {
            for (BMKPlanNode* tempNode in plan.wayPoints) {
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item = [[RouteAnnotation alloc]init];
                item.coordinate = tempNode.pt;
                item.type = 5;
                item.title = tempNode.name;
                [self.mapV addAnnotation:item];
            }
        }
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        // 通过points构建BMKPolyline
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [self.mapV addOverlay:polyLine]; // 添加路线overlay
        delete []temppoints;
        [self mapViewFitPolyLine:polyLine];
    }
}

#pragma mark - private motheds
//初始化数据
- (void)initData {
    
    self.locService = [[BMKLocationService alloc] init];
    self.routeSearch = [[BMKRouteSearch alloc]init];
    
    [self.locService startUserLocationService];
    self.mapV.showsUserLocation = NO;//先关闭显示的定位图层
    self.mapV.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    self.mapV.showsUserLocation = YES;//显示定位图层
}


- (void)addOilState {
    
    BMKPointAnnotation *po1 = [[BMKPointAnnotation alloc] init];
    po1.coordinate = userCoor;
    [_mapV addAnnotation:po1];
    
    BMKPointAnnotation *po2 = [[BMKPointAnnotation alloc] init];
    CLLocationCoordinate2D coor2;
    coor2.latitude = 30.56 - 0.02;
    coor2.longitude = 104.04 - 0.01;
    po2.coordinate = coor2;
    [_mapV addAnnotation:po2];
    
    
}

- (void)addLine {
    
    BMKPlanNode *startNode = [[BMKPlanNode alloc] init];
    startNode.pt = userCoor;
    
    BMKPlanNode* endNode = [[BMKPlanNode alloc]init];
    CLLocationCoordinate2D coor2;
    coor2.latitude = 30.56 - 0.02;
    coor2.longitude = 104.04 - 0.01;
    endNode.pt = coor2;
    
    BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc]init];
    drivingRouteSearchOption.from = startNode;
    drivingRouteSearchOption.to = endNode;
    BOOL flag = [_routeSearch drivingSearch:drivingRouteSearchOption];
    if(flag)
    {
        NSLog(@"car检索发送成功");
    }
    else
    {
        NSLog(@"car检索发送失败");
    }
}

//根据polyline设置地图范围
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    CGFloat ltX, ltY, rbX, rbY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    
    ltX = pt.x, ltY = pt.y;
    rbX = pt.x, rbY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        if (pt.x < ltX) {
            ltX = pt.x;
        }
        if (pt.x > rbX) {
            rbX = pt.x;
        }
        if (pt.y > ltY) {
            ltY = pt.y;
        }
        if (pt.y < rbY) {
            rbY = pt.y;
        }
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(ltX , ltY);
    rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY);
    [self.mapV setVisibleMapRect:rect];
    self.mapV.zoomLevel = self.mapV.zoomLevel - 0.3;
}

#pragma mark - setters and getters
- (BMKMapView *)mapV {
    
    if (_mapV == nil) {
        
        _mapV = [[BMKMapView alloc] initWithFrame:self.bounds];
    }
    return _mapV;
}

@end
